import { logger } from '../types/constants'
import { ToolKit } from './utils/toolkit'

/**
 * 定时器任务配置
 */
interface TimerTaskConfig {
  id: string // 任务唯一标识
  callback: () => void // 回调函数
  immediate?: boolean // 是否立即执行第一次
  autoStart?: boolean // 是否自动启动
}

/**
 * 一次性定时器配置
 */
interface TimeoutTaskConfig extends TimerTaskConfig {
  delay: number // 延迟时间（毫秒）- 一次性任务专用
  interval?: never // 循环任务不能有delay
}

/**
 * 循环定时器配置
 */
interface IntervalTaskConfig extends TimerTaskConfig {
  interval: number // 间隔时间（毫秒）- 循环任务专用
  maxRuns?: number // 最大执行次数
  delay?: never // 一次性任务不能有interval
}

/**
 * 定时器任务配置（联合类型）
 */
type TimerTaskConfigUnion = TimeoutTaskConfig | IntervalTaskConfig

/**
 * 类型守卫：检查是否为一次性任务
 */
function isTimeoutTask(config: TimerTaskConfigUnion): config is TimeoutTaskConfig {
  return 'delay' in config && config.delay !== undefined
}

/**
 * 类型守卫：检查是否为循环任务
 */
function isIntervalTask(config: TimerTaskConfigUnion): config is IntervalTaskConfig {
  return 'interval' in config && config.interval !== undefined
}

/**
 * 定时器任务状态
 */
interface TimerTaskState {
  id: string
  type: 'timeout' | 'interval'
  delay: number
  interval?: number
  runs: number
  maxRuns?: number
  startTime: number
  nextRunTime?: number
  isActive: boolean
}

/**
 * 计时器配置
 */
interface StopwatchConfig {
  id: string // 计时器唯一标识
  autoStart?: boolean // 是否自动开始
  precision?: number // 精度（毫秒，默认1ms）
  useHighPrecision?: boolean // 是否使用高精度模式（performance.now()）
  maxDuration?: number // 最大计时时长（毫秒，防溢出）
  stopOnLap?: boolean // 打点后是否停止计时器
}

/**
 * 计时器状态
 */
interface StopwatchState {
  id: string
  startTime?: number
  endTime?: number
  elapsed: number
  isRunning: boolean
  laps: LapRecord[]
  useHighPrecision: boolean
  maxDuration: number
  lastLapTime: number
  stopOnLap: boolean // 打点后是否停止
}

/**
 * 打点记录接口
 */
interface LapRecord {
  time: number // 打点时间（毫秒）
  note?: string // 备注信息
  interval: number // 与上次打点的间隔时间
  timestamp: number // 打点发生的时间戳
}

/**
 * 打点选项配置
 */
interface LapOptions {
  note?: string // 打点备注
  stopAfterLap?: boolean // 打点后是否停止计时器
}

interface LapResult {
  time: number
  stopped: boolean
}

/**
 * 计时器详细信息结果
 */
interface StopwatchDetailsResult {
  elapsed: number
  isRunning: boolean
  laps: LapRecord[]
  mode: 'high-precision' | 'standard'
  maxDuration: number
  remaining?: number
  totalLaps: number
  averageLapTime: number
  fastestLap?: number
  slowestLap?: number
}

/**
 * 性能监控配置
 */
interface PerformanceMonitorConfig {
  totalTimeouts: number
  totalIntervals: number
  activeTimeouts: number
  activeIntervals: number
}

export interface IntervalTaskProps {
  id: string
  interval: number
  running: boolean
}

/**
 * 定时器和计时器管理工具类
 *
 * @example
 * ```typescript
 * const timerManager = new TimerManager()
 *
 * // 创建一次性定时器
 * timerManager.setTimeout('task1', () => {
 *   console.log('5秒后执行')
 * }, 5000)
 *
 * // 创建循环定时器
 * timerManager.setInterval('task2', () => {
 *   console.log('每2秒执行一次')
 * }, 2000, { maxRuns: 5 })
 *
 * // 创建计时器
 * const stopwatch = timerManager.createStopwatch('sw1')
 * stopwatch.start()
 *
 * // 获取状态
 * console.log(timerManager.getState())
 *
 * // 销毁所有
 * timerManager.destroy()
 * ```
 */
export class TimerManager {
  readonly name: string = 'TimerManager'
  private static instance: TimerManager
  private timeouts: Map<string, number> = new Map()
  private intervals: Map<string, number> = new Map()
  private stopwatches: Map<string, StopwatchState> = new Map()
  private taskStates: Map<string, TimerTaskState> = new Map()

  // 性能监控
  private performanceMonitor: PerformanceMonitorConfig = {
    totalTimeouts: 0,
    totalIntervals: 0,
    activeTimeouts: 0,
    activeIntervals: 0,
  }

  /**
   * 获取单例实例
   */
  static getInstance(): TimerManager {
    if (!TimerManager.instance) {
      TimerManager.instance = new TimerManager()
    }
    return TimerManager.instance
  }

  /**
   * 创建一次性定时器
   * @param id - 定时器ID
   * @param callback - 回调函数
   * @param delay - 延迟时间（毫秒）
   * @param options - 配置选项
   * @returns 是否创建成功
   */
  setTimeout(
    id: string,
    callback: () => void,
    delay: number,
    options: Pick<TimeoutTaskConfig, 'immediate'>,
  ): boolean {
    if (this.timeouts.has(id)) {
      logger.warn(`[${this.name}] 定时器 ID 已存在: ${id}`)
      return false
    }

    const { immediate = false } = options

    if (immediate) {
      try {
        callback()
        logger.debug(`[${this.name}] 立即执行回调: ${id}`)
      }
      catch (error) {
        logger.error(`[${this.name}] 立即执行回调失败: ${id}`, error)
        return false
      }
    }

    const timeoutId = window.setTimeout(() => {
      try {
        callback()
        logger.debug(`[${this.name}] 定时器执行完成: ${id}`)
      }
      catch (error) {
        logger.error(`[${this.name}] 定时器执行错误: ${id}`, error)
      }
      finally {
        this.clearTimeout(id)
      }
    }, delay)

    this.timeouts.set(id, timeoutId)

    // 记录状态
    this.taskStates.set(id, {
      id,
      type: 'timeout',
      delay,
      runs: immediate ? 1 : 0,
      startTime: Date.now(),
      nextRunTime: Date.now() + delay,
      isActive: true,
    })

    this.performanceMonitor.totalTimeouts++
    this.performanceMonitor.activeTimeouts++

    logger.debug(`[${this.name}] 创建一次性定时器: ${id}`, { delay, immediate })
    return true
  }

  /**
   * 创建循环定时器
   * @param id - 定时器ID
   * @param callback - 回调函数
   * @param interval - 间隔时间（毫秒）
   * @param options - 配置选项
   * @returns 是否创建成功
   */
  setInterval(
    id: string,
    callback: () => void,
    interval: number,
    options: Pick<IntervalTaskConfig, 'immediate' | 'maxRuns'>,
  ): boolean {
    if (this.intervals.has(id)) {
      logger.warn(`[${this.name}] 循环定时器 ID 已存在: ${id}`)
      return false
    }

    const { immediate = false, maxRuns } = options
    let runs = 0

    const executeCallback = () => {
      try {
        callback()
        runs++
        logger.debug(`[${this.name}] 循环定时器执行: ${id} (第${runs}次)`)

        // 更新状态
        const state = this.taskStates.get(id)
        if (state) {
          state.runs = runs
          state.nextRunTime = Date.now() + interval
        }

        // 检查执行次数限制
        if (maxRuns && runs >= maxRuns) {
          logger.info(`[${this.name}] 循环定时器达到最大执行次数: ${id} (${maxRuns}次)`)
          this.clearInterval(id)
        }
      }
      catch (error) {
        logger.error(`[${this.name}] 循环定时器执行错误: ${id}`, error)
      }
    }

    if (immediate) {
      executeCallback()
    }

    const intervalId = window.setInterval(executeCallback, interval)
    this.intervals.set(id, intervalId)

    // 记录状态
    this.taskStates.set(id, {
      id,
      type: 'interval',
      delay: interval,
      interval,
      runs: immediate ? 1 : 0,
      maxRuns,
      startTime: Date.now(),
      nextRunTime: Date.now() + interval,
      isActive: true,
    })

    this.performanceMonitor.totalIntervals++
    this.performanceMonitor.activeIntervals++

    logger.debug(`[${this.name}] 创建循环定时器: ${id}`, { interval, maxRuns, immediate })
    return true
  }

  /**
   * 创建高级定时任务
   */
  createTimerTask(config: TimerTaskConfigUnion): boolean {
    const { id, callback, immediate = false } = config

    // 参数验证
    if (!isTimeoutTask(config) && !isIntervalTask(config)) {
      logger.error(`[${this.name}] 定时任务配置错误: ${id}，必须指定 delay 或 interval`)
      return false
    }

    if (isTimeoutTask(config) && isIntervalTask(config)) {
      logger.error(`[${this.name}] 定时任务配置冲突: ${id}，不能同时指定 delay 和 interval`)
      return false
    }

    if (isTimeoutTask(config)) {
      // 一次性任务
      const { delay } = config

      if (delay <= 0) {
        logger.error(`[${this.name}] 延迟时间必须大于0: ${id}`)
        return false
      }

      return this.setTimeout(id, callback, delay, { immediate })
    }
    else if (isIntervalTask(config)) {
      // 循环任务
      const { interval, maxRuns } = config

      if (interval <= 0) {
        logger.error(`[${this.name}] 间隔时间必须大于0: ${id}`)
        return false
      }

      return this.setInterval(id, callback, interval, { immediate, maxRuns })
    }

    return false
  }

  /**
   * 清除一次性定时器
   * @param id - 定时器ID
   * @returns 是否清除成功
   */
  clearTimeout(id: string): boolean {
    const timeout = this.timeouts.get(id)

    if (!timeout) {
      logger.warn(`[${this.name}] 定时器不存在: ${id}`)
      return false
    }

    clearTimeout(timeout)
    this.timeouts.delete(id)

    // 更新状态
    const state = this.taskStates.get(id)
    if (state) {
      state.isActive = false
    }

    this.performanceMonitor.activeTimeouts = Math.max(0, this.performanceMonitor.activeTimeouts - 1)

    logger.debug(`[${this.name}] 清除定时器: ${id}`)
    return true
  }

  /**
   * 清除循环定时器
   * @param id - 定时器ID
   * @param safeClean - 是否安全清除（检查是否存在）
   * @returns 是否清除成功
   */
  clearInterval(id: string, safeClean: boolean = false): boolean {
    if (safeClean && !this.checkInterval(id))
      return false

    const interval = this.intervals.get(id)

    if (!interval) {
      logger.warn(`[${this.name}] 循环定时器不存在: ${id}`)
      return false
    }

    clearInterval(interval)
    this.intervals.delete(id)

    // 更新状态
    const state = this.taskStates.get(id)
    if (state) {
      state.isActive = false
    }

    this.performanceMonitor.activeIntervals = Math.max(0, this.performanceMonitor.activeIntervals - 1)

    logger.debug(`[${this.name}] 清除循环定时器: ${id}`)
    return true
  }

  /**
   * 检查循环定时器是否存在
   * @param id - 定时器ID
   * @returns 是否存在
   */
  checkInterval(id: string): boolean {
    return this.intervals.has(id)
  }

  /**
   * 创建计时器
   * @param id - 计时器ID
   * @param config - 计时器配置
   * @returns 计时器控制器
   */
  createStopwatch(id: string, config: Omit<StopwatchConfig, 'id'> = {}): StopwatchController {
    if (this.stopwatches.has(id)) {
      logger.warn(`[${this.name}] 计时器ID已存在: ${id}`)
      // 返回已存在的计时器控制器
      return new StopwatchController(this, id)
    }

    const { autoStart = false, precision = 1, useHighPrecision = false, maxDuration = Number.MAX_SAFE_INTEGER, stopOnLap = false } = config

    const stopwatchState: StopwatchState = {
      id,
      elapsed: 0,
      isRunning: false,
      laps: [],
      useHighPrecision,
      maxDuration,
      lastLapTime: 0,
      stopOnLap,
    }

    this.stopwatches.set(id, stopwatchState)

    if (autoStart) {
      this.startStopwatch(id)
    }

    logger.debug(`[${this.name}] 创建计时器: ${id}`, {
      autoStart,
      precision,
      useHighPrecision,
      maxDuration: maxDuration === Number.MAX_SAFE_INTEGER ? '无限制' : `${maxDuration}ms`,
      stopOnLap,
    })
    return new StopwatchController(this, id)
  }

  /**
   * 开始计时器
   * @param id - 计时器ID
   * @returns 是否启动成功
   */
  startStopwatch(id: string): boolean {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      logger.warn(`[${this.name}] 计时器不存在: ${id}`)
      return false
    }

    if (stopwatch.isRunning) {
      logger.warn(`[${this.name}] 计时器已在运行: ${id}`)
      return false
    }

    const currentTime = ToolKit.time.getCurrentTime(stopwatch.useHighPrecision)
    stopwatch.startTime = currentTime - stopwatch.elapsed
    stopwatch.isRunning = true
    stopwatch.lastLapTime = currentTime

    logger.debug(`[${this.name}] 开始计时器: ${id}`, {
      mode: stopwatch.useHighPrecision ? '高精度' : '标准',
      maxDuration: stopwatch.maxDuration,
    })
    return true
  }

  /**
   * 暂停计时器
   * @param id - 计时器ID
   * @returns 是否暂停成功
   */
  pauseStopwatch(id: string): boolean {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      logger.warn(`[${this.name}] 计时器不存在: ${id}`)
      return false
    }

    if (!stopwatch.isRunning) {
      logger.warn(`[${this.name}] 计时器未运行: ${id}`)
      return false
    }

    if (stopwatch.startTime) {
      const currentTime = ToolKit.time.getCurrentTime(stopwatch.useHighPrecision)
      stopwatch.elapsed = currentTime - stopwatch.startTime

      // 检查是否超过最大时长
      if (stopwatch.elapsed > stopwatch.maxDuration) {
        logger.warn(`[${this.name}] 计时器超过最大时长: ${id}`, {
          elapsed: stopwatch.elapsed,
          maxDuration: stopwatch.maxDuration,
        })
        stopwatch.elapsed = stopwatch.maxDuration
      }
    }
    stopwatch.isRunning = false

    logger.debug(`[${this.name}] 暂停计时器: ${id}`, {
      elapsed: ToolKit.time.formatElapsedTime(stopwatch.elapsed),
      mode: stopwatch.useHighPrecision ? '高精度' : '标准',
    })
    return true
  }

  /**
   * 重置计时器
   * @param id - 计时器ID
   * @returns 是否重置成功
   */
  resetStopwatch(id: string): boolean {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      logger.warn(`[${this.name}] 计时器不存在: ${id}`)
      return false
    }

    stopwatch.startTime = undefined
    stopwatch.endTime = undefined
    stopwatch.elapsed = 0
    stopwatch.isRunning = false
    stopwatch.laps = []

    logger.debug(`[${this.name}] 重置计时器: ${id}`)
    return true
  }

  /**
   * 记录计时点（打点）
   * @param id - 计时器ID
   * @param options - 打点选项
   * @returns 打点时间（毫秒）
   */
  lapStopwatch(id: string, options: LapOptions = {}): LapResult {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      logger.warn(`[${this.name}] 计时器不存在: ${id}`)
      return { time: 0, stopped: false }
    }

    if (!stopwatch.isRunning) {
      logger.warn(`[${this.name}] 计时器未运行，无法打点: ${id}`)
      return { time: 0, stopped: false }
    }

    const currentTime = ToolKit.time.getCurrentTime(stopwatch.useHighPrecision)
    const totalElapsed = stopwatch.startTime ? currentTime - stopwatch.startTime : 0

    // 计算本次打点间隔（从上一次打点到现在的时间）
    const lapInterval = stopwatch.lastLapTime > 0 ? currentTime - stopwatch.lastLapTime : totalElapsed
    stopwatch.lastLapTime = currentTime

    // 创建打点记录
    const lapRecord: LapRecord = {
      time: totalElapsed,
      note: options.note,
      interval: lapInterval,
      timestamp: Date.now(), // 记录实际发生时间
    }

    stopwatch.laps.push(lapRecord)

    let stopped = false

    // 检查是否需要停止（选项优先，然后是全局设置）
    const shouldStop = options.stopAfterLap ?? stopwatch.stopOnLap
    if (shouldStop) {
      this.pauseStopwatch(id)
      stopped = true
      logger.info(`[${this.name}] 打点后自动停止计时器: ${id}`)
    }

    logger.debug(`[${this.name}] 记录计时点: ${id}`, {
      lapTime: ToolKit.time.formatElapsedTime(lapRecord.time),
      note: options.note ?? '',
      lapInterval: ToolKit.time.formatElapsedTime(lapRecord.interval),
      totalLaps: stopwatch.laps.length,
      stopped,
    })

    return { time: totalElapsed, stopped }
  }

  /**
   * 获取计时器经过的时间
   * @param id - 计时器ID
   * @returns 经过的时间（毫秒）
   */
  getStopwatchElapsed(id: string): number {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch)
      return 0

    if (stopwatch.isRunning && stopwatch.startTime) {
      const currentTime = ToolKit.time.getCurrentTime(stopwatch.useHighPrecision)
      const elapsed = currentTime - stopwatch.startTime

      // 检查最大时长限制
      if (elapsed > stopwatch.maxDuration) {
        logger.warn(`[${this.name}] 计时器超过最大时长限制: ${id}`)
        this.pauseStopwatch(id) // 自动暂停
        return stopwatch.maxDuration
      }

      return elapsed
    }

    return stopwatch.elapsed
  }

  /**
   * 获取计时器详细信息
   */
  getStopwatchDetails(id: string): StopwatchDetailsResult | null {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch)
      return null

    const elapsed = this.getStopwatchElapsed(id)
    const remaining = stopwatch.maxDuration - elapsed

    // 计算统计信息
    const lapTimes = stopwatch.laps.map(lap => lap.interval)
    const totalLapTime = lapTimes.reduce((sum, time) => sum + time, 0)
    const averageLapTime = lapTimes.length > 0 ? totalLapTime / lapTimes.length : 0
    const fastestLap = lapTimes.length > 0 ? Math.min(...lapTimes) : undefined
    const slowestLap = lapTimes.length > 0 ? Math.max(...lapTimes) : undefined

    return {
      elapsed,
      isRunning: stopwatch.isRunning,
      laps: [...stopwatch.laps],
      mode: stopwatch.useHighPrecision ? 'high-precision' : 'standard',
      maxDuration: stopwatch.maxDuration,
      remaining: remaining > 0 ? remaining : 0,
      totalLaps: stopwatch.laps.length,
      averageLapTime,
      fastestLap,
      slowestLap,
    }
  }

  /**
   * 获取特定打点记录
   * @param id - 计时器ID
   * @param lapIndex - 打点索引（从0开始）
   * @returns 打点记录
   */
  getLapRecord(id: string, lapIndex: number): LapRecord | null {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch || lapIndex < 0 || lapIndex >= stopwatch.laps.length) {
      return null
    }

    return { ...stopwatch.laps[lapIndex] }
  }

  /**
   * 根据备注搜索打点记录
   * @param id - 计时器ID
   * @param noteKeyword - 备注关键词
   * @returns 匹配的打点记录
   */
  searchLapsByNote(id: string, noteKeyword: string): LapRecord[] {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      return []
    }

    const keyword = noteKeyword.toLowerCase()
    return stopwatch.laps.filter(lap =>
      lap.note && lap.note.toLowerCase().includes(keyword),
    ).map(lap => ({ ...lap }))
  }

  /**
   * 设置计时器打点后停止配置
   * @param id - 计时器ID
   * @param stopOnLap - 是否在打点后停止
   * @returns 是否设置成功
   */
  setStopOnLap(id: string, stopOnLap: boolean): boolean {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      logger.warn(`[${this.name}] 计时器不存在: ${id}`)
      return false
    }

    stopwatch.stopOnLap = stopOnLap
    logger.debug(`[${this.name}] 设置打点停止模式: ${id}`, { stopOnLap })

    return true
  }

  /**
   * 设置计时器最大时长
   */
  setStopwatchMaxDuration(id: string, maxDuration: number): boolean {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      logger.warn(`[${this.name}] 计时器不存在: ${id}`)
      return false
    }

    stopwatch.maxDuration = maxDuration
    logger.debug(`[${this.name}] 设置计时器最大时长: ${id}`, { maxDuration })

    return true
  }

  /**
   * 切换计时器精度模式
   */
  toggleStopwatchPrecision(id: string, useHighPrecision: boolean): boolean {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      logger.warn(`[${this.name}] 计时器不存在: ${id}`)
      return false
    }

    if (stopwatch.isRunning) {
      logger.warn(`[${this.name}] 计时器运行中无法切换精度模式: ${id}`)
      return false
    }

    stopwatch.useHighPrecision = useHighPrecision
    logger.debug(`[${this.name}] 切换计时器精度模式: ${id}`, {
      mode: useHighPrecision ? '高精度' : '标准',
    })

    return true
  }

  /**
   * 清除所有打点记录
   * @param id - 计时器ID
   * @returns 是否清除成功
   */
  clearLaps(id: string): boolean {
    const stopwatch = this.stopwatches.get(id)
    if (!stopwatch) {
      logger.warn(`[${this.name}] 计时器不存在: ${id}`)
      return false
    }

    const lapCount = stopwatch.laps.length
    stopwatch.laps = []
    stopwatch.lastLapTime = 0

    logger.debug(`[${this.name}] 清除打点记录: ${id}`, { clearedLaps: lapCount })
    return true
  }

  /**
   * 销毁计时器
   * @param id - 计时器ID
   * @returns 是否销毁成功
   */
  destroyStopwatch(id: string): boolean {
    const exists = this.stopwatches.has(id)
    if (!exists) {
      return false
    }

    this.stopwatches.delete(id)
    logger.debug(`[${this.name}] 销毁计时器: ${id}`)
    return true
  }

  /**
   * 获取所有定时器状态
   * @returns 状态信息
   */
  getState(): {
    timeouts: string[]
    intervals: string[]
    stopwatches: string[]
    performance: PerformanceMonitorConfig
    taskStates: TimerTaskState[]
    stopwatchStates: StopwatchState[]
  } {
    const taskStates: TimerTaskState[] = []
    this.taskStates.forEach((state) => {
      if (state.isActive) {
        taskStates.push({ ...state })
      }
    })

    const stopwatchStates: StopwatchState[] = []
    this.stopwatches.forEach((state) => {
      stopwatchStates.push({ ...state })
    })

    return {
      timeouts: Array.from(this.timeouts.keys()),
      intervals: Array.from(this.intervals.keys()),
      stopwatches: Array.from(this.stopwatches.keys()),
      performance: { ...this.performanceMonitor },
      taskStates,
      stopwatchStates,
    }
  }

  /**
   * 销毁所有定时器和计时器
   */
  destroy(): void {
    // 清除所有定时器
    this.timeouts.forEach((timeout, id) => {
      clearTimeout(timeout)
      logger.debug(`[${this.name}] 销毁定时器: ${id}`)
    })

    this.intervals.forEach((interval, id) => {
      clearInterval(interval)
      logger.debug(`[${this.name}] 销毁循环定时器: ${id}`)
    })

    // 清空所有集合
    this.timeouts.clear()
    this.intervals.clear()
    this.stopwatches.clear()
    this.taskStates.clear()

    // 重置性能监控
    this.performanceMonitor.activeTimeouts = 0
    this.performanceMonitor.activeIntervals = 0

    logger.info(`[${this.name}] 定时器管理器已完全销毁`)
  }
}

/**
 * 计时器控制器类（提供更友好的API）
 */
export class StopwatchController {
  constructor(
    private manager: TimerManager,
    private id: string,
  ) {}

  /**
   * 开始计时
   */
  start(): boolean {
    return this.manager.startStopwatch(this.id)
  }

  /**
   * 暂停计时
   */
  pause(): boolean {
    return this.manager.pauseStopwatch(this.id)
  }

  /**
   * 重置计时器
   */
  reset(): boolean {
    return this.manager.resetStopwatch(this.id)
  }

  /**
   * 记录计时点
   */
  lap(options: LapOptions = {}): LapResult {
    return this.manager.lapStopwatch(this.id, options)
  }

  /**
   * 快速打点（带备注）
   */
  lapWithNote(note: string, stopAfterLap: boolean = false): number {
    const result = this.manager.lapStopwatch(this.id, { note, stopAfterLap })
    return result.time
  }

  /**
   * 设置打点后停止模式
   */
  setStopOnLap(stopOnLap: boolean): boolean {
    return this.manager.setStopOnLap(this.id, stopOnLap)
  }

  /**
   * 获取经过的时间
   */
  getElapsed(): number {
    return this.manager.getStopwatchElapsed(this.id)
  }

  /**
   * 获取详细信息
   */
  getDetails(): StopwatchDetailsResult | null {
    return this.manager.getStopwatchDetails(this.id)
  }

  /**
   * 获取特定打点记录
   */
  getLap(lapIndex: number): LapRecord | null {
    return this.manager.getLapRecord(this.id, lapIndex)
  }

  /**
   * 根据备注搜索打点记录
   */
  searchLaps(noteKeyword: string): LapRecord[] {
    return this.manager.searchLapsByNote(this.id, noteKeyword)
  }

  /**
   * 清除所有打点记录
   */
  clearLaps(): boolean {
    return this.manager.clearLaps(this.id)
  }

  /**
   * 获取打点统计信息
   */
  getLapStats(): {
    total: number
    average: number
    fastest?: number
    slowest?: number
    totalTime: number
  } {
    const details = this.getDetails()
    if (!details) {
      return { total: 0, average: 0, totalTime: 0 }
    }

    return {
      total: details.totalLaps,
      average: details.averageLapTime,
      fastest: details.fastestLap,
      slowest: details.slowestLap,
      totalTime: details.elapsed,
    }
  }

  /**
   * 设置最大时长
   */
  setMaxDuration(maxDuration: number): boolean {
    return this.manager.setStopwatchMaxDuration(this.id, maxDuration)
  }

  /**
   * 切换精度模式
   */
  togglePrecision(useHighPrecision: boolean): boolean {
    return this.manager.toggleStopwatchPrecision(this.id, useHighPrecision)
  }

  /**
   * 销毁计时器
   */
  destroy(): boolean {
    return this.manager.destroyStopwatch(this.id)
  }

  /**
   * 获取计时器状态
   */
  getState(): StopwatchState | undefined {
    return (this.manager as any).stopwatches.get(this.id)
  }
}
